const Storage = require('../../utils/storage')

Page({
  data: {
    doctorId: '',
    tags: [],
    selectedTagId: '',      // 当前选中的评价标签ID
    selectedRating: 'good', // 当前选中的好评度: good/normal/bad
    reviews: [],           // 评价列表
    lastRequest: {         // 记录上次请求的参数，用于防止重复请求
      tagId: '',
      rating: ''
    },
    ratingStats: {  // 添加好评度统计
      good: 0,
      normal: 0,
      bad: 0
    }
  },

  onLoad(options) {
    const { doctorId, tagId } = options;
    
    if (!doctorId) {
      wx.showToast({
        title: '参数错误',
        icon: 'error'
      });
      return;
    }

    this.setData({
      doctorId,
      selectedTagId: parseInt(tagId, 10)
    });
    
    const cachedTags = Storage.getDoctorTags(doctorId);

    if (cachedTags && cachedTags.length > 0) {
      this.setData({ 
        tags: cachedTags,
        selectedTagId: tagId || cachedTags[0].id
      }, () => {
        this.fetchReviews();
      });
    } else {
      this.fetchTags(doctorId, tagId);
    }
  },

  // 获取评价标签
  fetchTags(doctorId, initialTagId) {
    wx.request({
      url: `https://your-api-domain/api/v1/doctors/${doctorId}/review-tags`,
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Authorization': Storage.getAuthToken()
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 0 && res.data.data?.length > 0) {
          const tags = res.data.data;
          Storage.setDoctorTags(doctorId, tags);
          const validTagId = initialTagId || tags[0].id;
          this.setData({ 
            tags,
            selectedTagId: validTagId
          }, () => {
            this.fetchReviews();
          });
        } else {
          this.useMockTags(doctorId, initialTagId);
        }
      },
      fail: (err) => {
        this.useMockTags(doctorId, initialTagId);
      }
    });
  },

  // 获取评价列表
  fetchReviews() {
    
    const { selectedTagId, selectedRating, lastRequest, doctorId } = this.data;
    
    if (lastRequest.tagId === selectedTagId && lastRequest.rating === selectedRating) {
      return;
    }

    wx.request({
      url: 'https://your-api-domain/api/v1/reviews',
      method: 'GET',
      data: {
        doctorId,
        tagId: selectedTagId,
        rating: selectedRating
      },
      header: {
        'content-type': 'application/json',
        'Authorization': Storage.getAuthToken()
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 0) {
          const reviews = res.data.data.map(this.processReview.bind(this));
          this.setData({ 
            reviews,
            lastRequest: {
              tagId: selectedTagId,
              rating: selectedRating
            }
          }, () => {
            this.updateRatingStats();
          });
        } else {
          this.useMockReviews();
        }
      },
      fail: (err) => {
        this.useMockReviews();
      }
    });
  },

  // 处理评价数据
  processReview(review) {
    const formatDate = (dateString) => {
      const date = new Date(dateString);
      return `${date.getMonth() + 1}月${date.getDate()}日`;
    };

    return {
      ...review,
      phone: review.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2'),
      formattedDate: formatDate(review.date)
    };
  },

  // 评价标签点击事件
  onTagSelect(e) {
    
    const tagId = e.currentTarget.dataset.id;
    if (this.data.selectedTagId === tagId) {
      return;
    }
    
    this.setData({ 
      selectedTagId: tagId,
      reviews: [],
      selectedRating: 'good'
    }, () => {
      this.fetchReviews();
    });
  },

  // 好评度标签点击事件
  onRatingSelect(e) {
    const rating = e.currentTarget.dataset.rating;
    // 如果点击的是当前选中的好评度，不做处理
    if (this.data.selectedRating === rating) {
      return;
    }
    
    this.setData({ 
      selectedRating: rating,
      // 清空上一次的评价数据
      reviews: []
    }, () => {
      this.fetchReviews();
    });
  },

  // 模拟标签数据
  useMockTags(doctorId, initialTagId) {
    const mockTags = [
      { id: 'tag1', tag: '头痛', count: 12 },
      { id: 'tag2', tag: '胸闷', count: 8 },
      { id: 'tag3', tag: '眩晕', count: 6 },
      { id: 'tag4', tag: '高血压', count: 15 },
      { id: 'tag5', tag: '失眠', count: 9 }
    ];
    
    Storage.setDoctorTags(doctorId, mockTags);
    
    this.setData({ 
      tags: mockTags,
      selectedTagId: initialTagId || mockTags[0].id
    }, () => {
      this.fetchReviews();
    });
  },

  // 模拟评价数据
  useMockReviews() {
    const currentTag = this.data.tags.find(t => t.id == this.data.selectedTagId);

    if (!currentTag) return;

    // 生成随机的好评度分布
    const total = currentTag.count;
    const goodCount = Math.floor(total * 0.7);  // 70% 好评
    const normalCount = Math.floor(total * 0.2); // 20% 一般
    const badCount = total - goodCount - normalCount; // 剩余差评

    const mockReviews = [];
    
    // 生成好评
    for (let i = 0; i < goodCount; i++) {
      mockReviews.push(this.createMockReview('good'));
    }
    // 生成一般评价
    for (let i = 0; i < normalCount; i++) {
      mockReviews.push(this.createMockReview('normal'));
    }
    // 生成差评
    for (let i = 0; i < badCount; i++) {
      mockReviews.push(this.createMockReview('bad'));
    }

    this.setData({ 
      reviews: mockReviews.map(this.processReview.bind(this)),
      lastRequest: {
        tagId: this.data.selectedTagId,
        rating: this.data.selectedRating
      }
    }, () => {
      this.updateRatingStats();
    });
  },

  // 添加创建模拟评价的辅助方法
  createMockReview(rating) {
    return {
      id: `review_${Math.random()}`,
      phone: `138${String(Math.floor(Math.random() * 100000000)).padStart(8, '0')}`,
      date: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000),
      content: '医生很专业，讲解详细，态度很好。',
      problem: '最近工作压力大导致经常性头痛，医生详细询问了症状。',
      rating: rating
    };
  },

  // 添加统计方法
  updateRatingStats() {
    const stats = {
      good: 0,
      normal: 0,
      bad: 0
    };

    this.data.reviews.forEach(review => {
      if (review.rating) {
        stats[review.rating]++;
      }
    });

    this.setData({ ratingStats: stats });
  }
}); 